﻿using Autofac;
using Common.Framework.Core.Extension;
using Common.Framework.Core.Serilog;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using SqlSugar.IOC;

namespace Common.Framework.Core.SqlSugar
{
    public static class SqlSugarConfigure
    {
        /// <summary>
        /// 配置sqlsugar
        /// </summary>
        /// <param name="services"></param>
        public static IServiceCollection ConfigureSqlSugar(this IServiceCollection services, IConfiguration Configuration)
        {
            services.AddSingleton(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            //先获取ConnectionString下配置是所有链接字符串,循环注入
            Dictionary<string, string> connectionStringDic = ConfigurationExtension.GetSection<Dictionary<string, string>>("ConnectionString");
            string dbType = Configuration.GetSection("ConnectionString:DatabaseType").Value; // ConfigurationExtension.Configuration["ConnectionString:DatabaseType"]
            foreach (var conn in connectionStringDic)
            {
                if (conn.Key != "DatabaseType")
                {
                    services.AddSqlSugar(new IocConfig()
                    {
                        ConfigId = conn.Key,
                        ConnectionString = conn.Value,
                        DbType = dbType == null ? IocDbType.SqlServer : IocDbType.MySql, //目前只支持sqlserver和mysql
                        IsAutoCloseConnection = true,
                    });
                }
            }

            //设置参数
            services.ConfigurationSugar(db =>
            {
                foreach (var conn in connectionStringDic)
                {
                    if (conn.Key != "DatabaseType")
                    {
                        db.GetConnection(conn.Key).Aop.OnLogExecuting = (sql, pars) =>
                        {
#if DEBUG
                            System.Console.WriteLine("\r\n");
                            System.Console.WriteLine("================DEBUG Start============");
                            //如果是测试环境,记录sql,用于调试和创建索引
                            var aspnetcore_environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
                            if (aspnetcore_environment == "Development")
                            {
                                var parameterName = db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value));
                                LoggerHelper.InformationSql(sql, parameterName);
                            }

                            System.Console.WriteLine("\r\n");
                            System.Console.WriteLine(sql + "\r\n" +
                             db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));

                            System.Console.WriteLine("\r\n\r\n");
                            System.Console.WriteLine("================DEBUG End============");

                            System.Diagnostics.Debug.WriteLine("\r\n");
                            System.Diagnostics.Debug.WriteLine("================DEBUG Start============");
                            System.Diagnostics.Debug.WriteLine("\r\n");
                            System.Diagnostics.Debug.WriteLine(sql + "\r\n" +
                                db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                            System.Diagnostics.Debug.WriteLine("\r\n");
                            System.Diagnostics.Debug.WriteLine("\r\n");
                            System.Diagnostics.Debug.WriteLine("================DEBUG End============");
#endif
                        };
                    }
                }
            });

            return services;
        }

        /// <summary>
        /// 注入sqlsugar
        /// </summary>
        /// <param name="builder"></param>
        public static void AutoRegisterSqlSugar(ContainerBuilder builder)
        {
            //先获取ConnectionString下配置是所有链接字符串,循环注入
            Dictionary<string, string> connectionStringDic = ConfigurationExtension.GetSection<Dictionary<string, string>>("ConnectionString");
            string dbType = ConfigurationExtension.Configuration["ConnectionString:DatabaseType"];
            foreach (var conn in connectionStringDic)
            {
                if (conn.Key != "DatabaseType")
                {
                    builder.Register<ISqlSugarClient>(x =>
                    {
                        var client = new SqlSugarClient(new ConnectionConfig()
                        {
                            ConfigId = conn.Key,
                            ConnectionString = conn.Value,
                            DbType = dbType == null ? DbType.SqlServer : DbType.MySql, //目前只支持sqlserver和mysql
                            IsAutoCloseConnection = true,
                        });

                        return client;

                    }).AsSelf().AsImplementedInterfaces().InstancePerLifetimeScope();
                }
            }
        }
    }
}
